package com.csw.android.androidtest.module.fragment;

import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import com.csw.android.androidtest.ui.LogViewFragment;
import com.csw.android.androidtest.view.LogView;
import com.csw.android.dev_utils.utils.FragmentHelper;

import java.util.HashSet;
import java.util.Set;

/**
 * 学自Glide图片加载任务生命周期管理，Glide之所以能成为android上最受欢迎的图片加载框架，除了因为他本身三级缓存，
 * 图片缓存处理（可以缓存http请求字节流、原图、缩放处理过的图），以及超强的自定义流数据解码（可以做解密）、可以
 * 自定义实现缓存数据编码解码等诸多特点，其任务管理也是框架的一个亮点。通过传入activity fragment构造
 * requestManager，内部通过向activity fragment添加一个无界面的fragment用于监听界面的生命周期变化，再pause的
 * 时候暂停界面加载图片，destroy的时候取消该界面的加载任务。
 * 这里参考其原理，监听fragment生命周期变化
 */
public class FragmentForLifecycleListenerTest extends LogViewFragment {

    @Override
    public void initData() {
        super.initData();
        LifecycleListenerFragment lifecycleListenerFragment = LifecycleListenerFragment.getInstance(getChildFragmentManager());
        lifecycleListenerFragment.addListener(
                new LifecycleListenerFragment.LifecycleListener() {
                    @Override
                    public void onLifeCycleChanged(int event) {
                        final LogView target = logView;
                        if(target!=null){
                            switch (event) {
                                case LifecycleListenerFragment.EVENT_ON_CREATE:
                                    target.addLog("EVENT_ON_CREATE");
                                    break;
                                case LifecycleListenerFragment.EVENT_ON_START:
                                    target.addLog("EVENT_ON_START");
                                    break;
                                case LifecycleListenerFragment.EVENT_ON_RESUME:
                                    target.addLog("EVENT_ON_RESUME");
                                    break;
                                case LifecycleListenerFragment.EVENT_ON_PAUSE:
                                    target.addLog("EVENT_ON_PAUSE");
                                    break;
                                case LifecycleListenerFragment.EVENT_ON_STOP:
                                    target.addLog("EVENT_ON_STOP");
                                    break;
                                case LifecycleListenerFragment.EVENT_ON_DESTROY:
                                    target.addLog("EVENT_ON_DESTROY");
                                    break;
                            }
                        }
                    }
                }
        );
    }

    public static final class LifecycleListenerFragment extends Fragment {
        //event取绝对值，若<=state，则符合该state
        public static final int EVENT_ON_CREATE = 2;
        public static final int EVENT_ON_START = 1;
        public static final int EVENT_ON_RESUME = 0;
        public static final int EVENT_ON_PAUSE = -1;//绝对值为1，对应started
        public static final int EVENT_ON_STOP = -2;//绝对值为2，对应created
        public static final int EVENT_ON_DESTROY = -3;//绝对值为3

        public static final int STATE_OUT_OF_LIFECYCLE = 3;//界面还处于生命周期之外
        public static final int STATE_CREATED = 2;//界面已经创建
        public static final int STATE_STARTED = 1;//界面已经可见
        public static final int STATE_RESUMED = 0;//界面已经处于前台

        public static LifecycleListenerFragment getInstance(FragmentManager fragmentManager) {
            return FragmentHelper.INSTANCE.getFragmentInstance(
                    fragmentManager,
                    LifecycleListenerFragment.class.getName(),
                    LifecycleListenerFragment.class
            );
        }

        //------------------------------------------------------------------------------------------
        private Set<LifecycleListener> listenerSet = new HashSet<>();

        synchronized public void addListener(LifecycleListener lifecycleListener) {
            listenerSet.add(lifecycleListener);
        }

        synchronized public void removeListener(LifecycleListener lifecycleListener) {
            listenerSet.remove(lifecycleListener);
        }

        synchronized private void dispatchEvent(int event) {
            for (LifecycleListener listener : listenerSet) {
                listener.onLifeCycleChanged(event);
            }
        }

        public int getState() {
            return state;
        }

        public boolean eventInState(int event, int state) {
            return Math.abs(event) <= state;
        }

        //------------------------------------------------------------------------------------------
        private int state = STATE_OUT_OF_LIFECYCLE;

        @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            state = STATE_CREATED;
            dispatchEvent(EVENT_ON_CREATE);
        }

        @Override
        public void onStart() {
            super.onStart();
            state = STATE_STARTED;
            dispatchEvent(EVENT_ON_START);
        }

        @Override
        public void onResume() {
            super.onResume();
            state = STATE_RESUMED;
            dispatchEvent(EVENT_ON_RESUME);
        }

        @Override
        public void onPause() {
            state = STATE_STARTED;
            dispatchEvent(EVENT_ON_PAUSE);
            super.onPause();
        }

        @Override
        public void onStop() {
            state = STATE_CREATED;
            dispatchEvent(EVENT_ON_STOP);
            super.onStop();
        }

        @Override
        public void onDestroy() {
            state = STATE_OUT_OF_LIFECYCLE;
            dispatchEvent(EVENT_ON_DESTROY);
            super.onDestroy();
        }

        public interface LifecycleListener {
            void onLifeCycleChanged(int event);
        }
    }
}
